package com.dtjd.playcoinmonkey.activities.main;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.dtjd.playcoinmonkey.MyApplication;
import com.dtjd.playcoinmonkey.R;
import com.dtjd.playcoinmonkey.activities.LoginActivity;
import com.dtjd.playcoinmonkey.bean.HttpParaBean;
import com.dtjd.playcoinmonkey.databinding.FragmentTicketBinding;
import com.dtjd.playcoinmonkey.utils.Network;
import com.dtjd.playcoinmonkey.utils.Tools;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class TicketFragment extends Fragment {
    private FragmentTicketBinding binding;
    int time=60;
    Handler handler=new Handler();
    Runnable runnable=new Runnable(){
        @SuppressLint({"SetTextI18n", "StringFormatMatches"})
        @Override
        public void run() {
            if (time>0){
                time--;
                handler.postDelayed(this, 1000);
                binding.ticketLookads.setText(String.format(getResources().getString(R.string.LookAdnextTime),time));
            }else {
                time=60;
                binding.ticketLookads.setEnabled(true);
                binding.ticketLookads.setText(getResources().getString(R.string.get_ticket_for_free));
            }
        }
    };
    private MainActivity activity;
    private ProgressDialog dialog;

    @RequiresApi(api = Build.VERSION_CODES.O)
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentTicketBinding.inflate(inflater, container, false);
        activity= (MainActivity) requireActivity();
//        binding.ticketIcon.setColorFilter(getResources().getColor(R.color.mainColor));
        binding.ticketLookads.setOnClickListener(v -> {
            if (dialog==null){
                dialog = new ProgressDialog(activity);
                dialog.setTitle(activity.getString(R.string.tips));
                dialog.setCanceledOnTouchOutside(false);
                dialog.setMessage(activity.getString(R.string.loading));
            }
            dialog.show();
            TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity);
            AdSlot adSlot = new AdSlot.Builder().setCodeId("946899756").setMediaExtra(MyApplication.sp.getString("token","")).setSupportDeepLink(true).setRewardName("Ticket").setRewardAmount(1).setUserID("user0").setExpressViewAcceptedSize(500,500).setOrientation(TTAdConstant.VERTICAL).build();
            mTTAdNative.loadRewardVideoAd(adSlot, new TTAdNative.RewardVideoAdListener() {
                @Override
                public void onError(int code, String message) {
                    dialog.dismiss();
                }
                @Override
                public void onRewardVideoCached(TTRewardVideoAd ttRewardVideoAd) {
                    dialog.dismiss();
                    ttRewardVideoAd.showRewardVideoAd(activity);
                }
                @Override
                public void onRewardVideoAdLoad(TTRewardVideoAd ad) {
                    ad.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
                        @Override
                        public void onAdShow() { }
                        @Override
                        public void onAdVideoBarClick() { }
                        @Override
                        public void onAdClose() { refresh(); }
                        @Override
                        public void onVideoComplete() { }
                        @Override
                        public void onVideoError() { }
                        @Override
                        public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName, int i1, String s1) {
                            if (rewardVerify) Tools.toast( getString(R.string.congratulation));
                        }
                        @Override
                        public void onSkippedVideo() {
                        }
                    });
                }
                @Override
                public void onRewardVideoCached() {
                }
            });

        });
        refresh();
        return binding.getRoot();
    }
    private void refresh() {
        List<HttpParaBean> para=new ArrayList<>();
        para.add(new HttpParaBean("token","token"));
        Network.post(para, "wbhMain/getTickets", new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
            }
            @SuppressLint("StringFormatMatches")
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                activity.runOnUiThread(() -> {
                    try {
                        JSONObject jo=new JSONObject(Objects.requireNonNull(response.body()).string());
                        if (jo.getInt("code")==1){
                            JSONObject jo1=jo.getJSONArray("datalist").getJSONObject(0);
                            binding.ticketNum.setText(String.format(getResources().getString(R.string.restTicket), jo1.getInt("ticket")));
                            time=jo1.getInt("time")/1000;
                            handler.postDelayed(runnable,0);
                            binding.ticketLookads.setEnabled(false);
                            binding.ticketDesc.setText(jo1.getString("description"));
                        }else {
                            SharedPreferences.Editor edit = MyApplication.sp.edit();
                            edit.putString("token","");
                            edit.apply();
                            Tools.toast( getResources().getString(R.string.loginToast));
                            startActivity(new Intent(activity, LoginActivity.class));
                            activity.finish();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
        handler.removeCallbacks(runnable);
    }
}